﻿using Chat.Common;
using SuperSocket.SocketBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChatServerLib
{
    /// <summary>
    /// 连接会话
    /// </summary>
    public class ChatSession : AppSession<ChatSession>
    {
        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName
        {
            get;
            set;
        }

        protected override void HandleUnknownRequest(SuperSocket.SocketBase.Protocol.StringRequestInfo requestInfo)
        {
            ResultStatus rs = new ResultStatus(ResultType.SEND);
            rs.Success = false;
            rs.Message = "Unknown request: " + requestInfo.Key;
            this.Send(rs.ToString());
        }

        protected override void OnSessionStarted()
        {
            base.OnSessionStarted();
        }

        protected override void OnSessionClosed(CloseReason reason)
        {
            if (!string.IsNullOrWhiteSpace(this.UserName))
            {
                this.Logger.DebugFormat("user {0} quit.", this.UserName);

                var sessions = this.AppServer.GetSessions(_ =>
                    !string.IsNullOrWhiteSpace(_.UserName)
                    && _.SessionID != this.SessionID);
                ResultStatus rs = new ResultStatus(ResultType.QUIT);
                rs.Message = string.Format("[{0}] quit.", this.UserName);
                rs.Data = this.UserName;

                string msg = rs.ToString();

                foreach (var item in sessions)
                {
                    item.Send(msg);
                }
            }

            base.OnSessionClosed(reason);
        }
    }
}
